#include "logindialog.h"
#include "protection.h"
#include <QApplication>
#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>
#include <QJsonParseError>
#include <QTextStream>
#include <QCryptographicHash>
#include <QDebug>

// 静态成员初始化
bool LoginDialog::s_isTrialUser = true;

LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent)
    , m_reply(nullptr)
    , m_apiManager(ApiManager::instance())
    , m_apiBase("https://ctdy123.com/api/auth/client/login")
{

    setWindowTitle(tr("登录 - 影谷长图处理大师"));
    setModal(true);
    setFixedSize(420, 400);

    // 初始化ConfigManager并执行配置迁移
    ConfigManager::initialize();
    ConfigManager::migrateFromUserIni();

    setupUI();
    setupStyles();
    setupConnections();
    loadFromIni();
}

LoginDialog::~LoginDialog()
{
    if (m_reply) {
        m_reply->deleteLater();
    }
    // 注意：不再删除m_apiManager，因为它是单例
}

void LoginDialog::setupUI()
{
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(18);
    m_mainLayout->setContentsMargins(40, 35, 40, 35);

    // 移除标题，遵循简洁设计原则
    m_mainLayout->addSpacing(25);

    // 邮箱输入框 - 无标签，更大更清晰
    m_editEmail = new QLineEdit(this);
    m_editEmail->setPlaceholderText(tr("邮箱地址"));
    m_editEmail->setObjectName("emailEdit");
    m_editEmail->setFixedHeight(44);
    m_mainLayout->addWidget(m_editEmail);

    m_mainLayout->addSpacing(8);

    // 密码输入框 - 无标签，更大更清晰
    m_editPassword = new QLineEdit(this);
    m_editPassword->setPlaceholderText(tr("密码"));
    m_editPassword->setEchoMode(QLineEdit::Password);
    m_editPassword->setObjectName("passwordEdit");
    m_editPassword->setFixedHeight(44);
    m_mainLayout->addWidget(m_editPassword);

    m_mainLayout->addSpacing(12);

    // 选项布局 - 更紧凑
    m_optionLayout = new QHBoxLayout();
    m_checkRememberEmail = new QCheckBox(tr("记住邮箱"), this);
    m_checkRememberPassword = new QCheckBox(tr("记住密码"), this);
    m_optionLayout->addWidget(m_checkRememberEmail);
    m_optionLayout->addWidget(m_checkRememberPassword);
    m_optionLayout->addStretch();
    m_mainLayout->addLayout(m_optionLayout);

    m_mainLayout->addSpacing(20);

    // 状态标签 - 放在按钮上方，初始显示提示信息
    m_labelStatus = new QLabel(this);
    m_labelStatus->setObjectName("statusLabel");
    m_labelStatus->setWordWrap(true);
    m_labelStatus->setAlignment(Qt::AlignCenter);
    m_labelStatus->setFixedHeight(50); // 增加高度，提供更多显示空间
    m_labelStatus->setText(tr("请输入您的账户信息进行登录"));
    m_labelStatus->setProperty("type", "info");
    m_labelStatus->setVisible(true);
    m_mainLayout->addWidget(m_labelStatus);

    m_mainLayout->addSpacing(15);

    // 按钮布局 - 只保留登录按钮，右对齐
    m_buttonLayout = new QHBoxLayout();
    m_btnLogin = new QPushButton(tr("登录"), this);
    m_btnLogin->setObjectName("loginButton");
    m_btnLogin->setDefault(true);
    m_btnLogin->setFixedHeight(36);
    m_btnLogin->setMinimumWidth(100);

    m_buttonLayout->addStretch();
    m_buttonLayout->addWidget(m_btnLogin);
    m_mainLayout->addLayout(m_buttonLayout);

    m_mainLayout->addSpacing(15);

    // 注册链接 - 更简洁
    m_labelRegister = new QLabel(this);
    m_labelRegister->setText(tr("<a href='#register'>还没有账号？前往官网注册</a>"));
    m_labelRegister->setAlignment(Qt::AlignCenter);
    m_labelRegister->setObjectName("registerLabel");
    m_mainLayout->addWidget(m_labelRegister);

    // 隐藏字段
    m_editApiBase = new QLineEdit(this);
    m_editApiBase->setText(m_apiBase);
    m_editApiBase->setVisible(false);

    m_editDeviceName = new QLineEdit(this);
    m_editDeviceName->setText(generateDeviceName());
    m_editDeviceName->setVisible(false);

    m_mainLayout->addStretch();

    // 应用初始状态样式
    m_labelStatus->style()->polish(m_labelStatus);
}

void LoginDialog::setupStyles()
{
    setStyleSheet(R"(
        QDialog {
            background-color: #F5F5F5;
        }

        QLineEdit {
            padding: 12px 16px;
            border: 1px solid #D5DBDB;
            border-radius: 6px;
            font-size: 13pt;
            background-color: white;
            color: #2C3E50;
        }

        QLineEdit:focus {
            border-color: #85929E;
            outline: none;
            background-color: #FAFAFA;
        }

        QLineEdit::placeholder {
            color: #AAB7B8;
        }

        #loginButton {
            background-color: #f0f0f0;
            color: #333;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 11pt;
        }

        #loginButton:hover {
            background-color: #e0e0e0;
            border-color: #999;
        }

        #loginButton:pressed {
            background-color: #d0d0d0;
        }

        #loginButton:disabled {
            background-color: #F7F9FA;
            color: #BDC3C7;
            border-color: #E5E8E8;
        }


        QCheckBox {
            font-size: 12pt;
            color: #5D6D7E;
            spacing: 8px;
        }

        QCheckBox::indicator {
            width: 18px;
            height: 18px;
            border: 1px solid #BDC3C7;
            border-radius: 3px;
            background-color: white;
        }

        QCheckBox::indicator:checked {
            background-color: #85929E;
            border-color: #85929E;
        }

        QCheckBox::indicator:hover {
            border-color: #85929E;
        }

        #statusLabel {
            font-size: 12pt;
            padding: 10px;
            border-radius: 4px;
            margin: 8px 0;
        }

        #statusLabel[type="error"] {
            background-color: #FADBD8;
            color: #C0392B;
            border: 1px solid #F1948A;
        }

        #statusLabel[type="success"] {
            background-color: #E8F8F5;
            color: #148F77;
            border: 1px solid #7DCEA0;
        }

        #statusLabel[type="loading"] {
            background-color: #EBF5FB;
            color: #2E86AB;
            border: 1px solid #AED6F1;
        }

        #statusLabel[type="info"] {
            background-color: #EBF5FB;
            color: #2E86AB;
            border: 1px solid #AED6F1;
        }

        #registerLabel {
            font-size: 12pt;
            color: #85929E;
        }

        #registerLabel a {
            color: #5D6D7E;
            text-decoration: none;
        }

        #registerLabel a:hover {
            color: #2C3E50;
            text-decoration: underline;
        }
    )");
}

void LoginDialog::setupConnections()
{
    connect(m_btnLogin, &QPushButton::clicked, this, &LoginDialog::onLoginClicked);
    connect(m_labelRegister, &QLabel::linkActivated, this, &LoginDialog::onRegisterLinkClicked);
    connect(m_checkRememberEmail, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberEmailChanged);
    connect(m_checkRememberPassword, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberPasswordChanged);

    // 回车键登录
    connect(m_editEmail, &QLineEdit::returnPressed, this, &LoginDialog::onLoginClicked);
    connect(m_editPassword, &QLineEdit::returnPressed, this, &LoginDialog::onLoginClicked);
}

void LoginDialog::loadFromIni()
{

    // 临时断开信号连接，避免加载时触发保存
    disconnect(m_checkRememberEmail, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberEmailChanged);
    disconnect(m_checkRememberPassword, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberPasswordChanged);

    // 加载API地址
    QString apiBase = ConfigManager::getApiBase();

    if (!apiBase.isEmpty()) {
        m_apiBase = apiBase;
        m_editApiBase->setText(apiBase);
    } else {
    }


    // 加载设备名称
    QString deviceName = ConfigManager::getDeviceName();
    if (!deviceName.isEmpty()) {
        m_editDeviceName->setText(deviceName);
        m_deviceName = deviceName;
    }

    // 加载记住邮箱选项和邮箱
    bool rememberEmail = ConfigManager::getRememberEmail();
    m_checkRememberEmail->setChecked(rememberEmail);

    // 总是尝试加载保存的邮箱，方便用户编辑
    QString email = ConfigManager::getUserEmail();
    if (!email.isEmpty()) {
        m_editEmail->setText(email);
        m_email = email;
    }

    // 加载记住密码选项和密码
    bool rememberPassword = ConfigManager::getRememberPassword();
    m_checkRememberPassword->setChecked(rememberPassword);

    if (rememberPassword) {
        QString encryptedPassword = ConfigManager::getEncryptedPassword();

        if (!encryptedPassword.isEmpty()) {
            try {
                // 解密密码
                QByteArray encrypted = QByteArray::fromBase64(encryptedPassword.toLatin1());
                QByteArray decrypted = Protection::decryptAuthData(encrypted);
                QString password = QString::fromUtf8(decrypted);
                m_editPassword->setText(password);
            } catch (...) {
                m_editPassword->clear();
            }
        } else {
        }
    } else {
    }

    // 加载已保存的token（现在使用安全存储）
    QString token = ConfigManager::getUserToken();
    if (!token.isEmpty()) {
        m_token = token;

        // 验证Token有效性
        SecureTokenManager& secureManager = SecureTokenManager::instance();
        qint64 remainingTime = secureManager.getTokenRemainingTime(m_email);
        if (remainingTime > 0) {
        } else {
            m_token.clear();
            ConfigManager::setUserToken(""); // 清除过期Token
        }
    } else {
    }


    // 重新连接信号连接
    connect(m_checkRememberEmail, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberEmailChanged);
    connect(m_checkRememberPassword, &QCheckBox::checkStateChanged, this, &LoginDialog::onRememberPasswordChanged);
}

void LoginDialog::saveToIni()
{

    // 保存API地址
    ConfigManager::setApiBase(m_apiBase);

    // 总是保存邮箱（登录成功后），方便下次使用
    QString currentEmail = m_editEmail->text().trimmed();
    if (!currentEmail.isEmpty()) {
        ConfigManager::setUserEmail(currentEmail);
    }

    // 保存密码

    if (m_checkRememberPassword->isChecked()) {
        QString password = m_editPassword->text();
        if (!password.isEmpty()) {
            try {
                // 加密密码
                QByteArray encrypted = Protection::encryptAuthData(password.toUtf8());
                QString encodedPassword = QString::fromLatin1(encrypted.toBase64());
                ConfigManager::setEncryptedPassword(encodedPassword);
            } catch (...) {
                ConfigManager::setEncryptedPassword("");
            }
        } else {
            ConfigManager::setEncryptedPassword("");
        }
    } else {
        ConfigManager::setEncryptedPassword("");
    }

    // 保存设备名称
    ConfigManager::setDeviceName(m_editDeviceName->text());

    // 保存记住选项
    bool rememberEmailState = m_checkRememberEmail->isChecked();
    bool rememberPasswordState = m_checkRememberPassword->isChecked();

    ConfigManager::setRememberEmail(rememberEmailState);
    ConfigManager::setRememberPassword(rememberPasswordState);


    // 保存token（现在使用安全加密存储）

    if (!m_token.isEmpty()) {
        // 验证Token格式和有效性
        if (m_token.length() >= 20) {  // 基本长度检查
            // 使用安全存储机制
            ConfigManager::setUserToken(m_token);

            // 验证存储是否成功
            QString verifyToken = ConfigManager::getUserToken();
            if (!verifyToken.isEmpty() && verifyToken == m_token) {

                // 检查Token过期时间
                SecureTokenManager& secureManager = SecureTokenManager::instance();
                qint64 remainingTime = secureManager.getTokenRemainingTime(m_email);
            } else {
            }
        } else {
        }
    } else {
    }

    // 同步到文件
    ConfigManager::sync();
}

bool LoginDialog::autoLoginAtStartup()
{

    // 确保ConfigManager已初始化
    ConfigManager::initialize();

    // 检查是否有保存的authToken和登录信息
    QString authToken = ConfigManager::getAuthToken();
    if (!authToken.isEmpty()) {
        m_token = authToken; // 保持向后兼容

        // 设置到ApiManager
        if (m_apiManager) {
            m_apiManager->setAuthToken(authToken);
        }

        QString email = ConfigManager::getUserEmail();
        if (!email.isEmpty()) {
            m_email = email;

            // 验证token有效性 - 尝试获取用户信息
            if (m_apiManager) {

                // 使用异步方式验证token
                QEventLoop loop;
                QTimer::singleShot(3000, &loop, &QEventLoop::quit); // 3秒超时

                bool tokenValid = false;
                // 预先声明连接对象
                QMetaObject::Connection connection1;
                QMetaObject::Connection connection2;

                // 使用安全的连接方式，避免lambda引用局部变量
                connection1 = connect(m_apiManager, &ApiManager::userProfileFetched,
                       [&](const QJsonObject& userProfile) {
                           tokenValid = true;

                           // 更新用户状态 - 关键修复点
                           QString utype = userProfile.value("type").toString();

                           if (utype.isEmpty() && userProfile.contains("subscription") && userProfile.value("subscription").isObject()) {
                               QJsonObject subscription = userProfile.value("subscription").toObject();
                               utype = subscription.value("type").toString();
                           }

                           QString freeStr = OBFUSCATE_STR("free");
                           s_isTrialUser = (utype.compare(freeStr, Qt::CaseInsensitive) == 0);

                           // 立即断开连接避免重复调用
                           disconnect(connection1);
                           disconnect(connection2);
                           loop.quit();
                       });

                connection2 = connect(m_apiManager, &ApiManager::networkError,
                       [&](const QString& error) {
                           // 立即断开连接避免重复调用
                           disconnect(connection1);
                           disconnect(connection2);
                           loop.quit();
                       });

                // 请求用户信息以验证token
                m_apiManager->fetchUserProfile();

                // 等待验证结果或超时
                loop.exec();

                if (tokenValid) {
                    // Token有效，进一步验证设备是否仍然存在（发送心跳）

                    QEventLoop heartbeatLoop;
                    QTimer::singleShot(5000, &heartbeatLoop, &QEventLoop::quit); // 5秒超时
                    bool deviceValid = false;

                    // 心跳成功表示设备有效
                    QMetaObject::Connection heartbeatConnection = connect(m_apiManager, &ApiManager::heartbeatSuccess,
                                                                        [&]() {
                        deviceValid = true;
                        heartbeatLoop.quit();
                    });

                    // 404或Token过期表示设备无效
                    QMetaObject::Connection deviceNotFoundConnection = connect(m_apiManager, &ApiManager::deviceNotFound,
                                                                                       [&]() {
                        deviceValid = false;
                        heartbeatLoop.quit();
                    });

                    // Token过期也表示设备无效
                    QMetaObject::Connection tokenExpiredConnection = connect(m_apiManager, &ApiManager::tokenExpired,
                                                                                    [&]() {
                        deviceValid = false;
                        heartbeatLoop.quit();
                    });

                    // 发送心跳请求
                    m_apiManager->sendHeartbeatForValidation(); // 手动触发一次心跳验证

                    // 等待心跳验证结果
                    heartbeatLoop.exec();

                    // 断开连接
                    disconnect(heartbeatConnection);
                    disconnect(deviceNotFoundConnection);
                    disconnect(tokenExpiredConnection);

                    if (deviceValid) {
                        // 设备有效，启动心跳保活
                        m_apiManager->startHeartbeat();
                        return true;
                    } else {
                        // 清除无效的Token，但保留邮箱和密码
                        ConfigManager::setAuthToken("");
                        ConfigManager::clearSubscriptionInfo();
                        // 注意：保留邮箱和密码，方便用户重新登录
                        return false;
                    }
                } else {

                    // 只清除无效的token，保留邮箱和其他登录信息
                    ConfigManager::setAuthToken("");
                    ConfigManager::setUserToken("");
                    // 不要清除邮箱，保留用户的登录信息
                    return false;
                }
            }
        } else {
        }
    } else {
    }

    return false;
}

void LoginDialog::onLoginClicked()
{

    if (!validateInput()) {
        return;
    }

    performLogin();
}

void LoginDialog::onRegisterLinkClicked()
{
    QDesktopServices::openUrl(QUrl("https://ctdy123.com/register"));
}

void LoginDialog::onRememberEmailChanged(int state)
{

    // 如果取消记住邮箱，清空输入框
    if (state == Qt::Unchecked) {
        m_editEmail->clear();
    }

    // 只保存记住选项状态，不保存邮箱（邮箱只在登录成功时保存）
    bool rememberEmail = m_checkRememberEmail->isChecked();
    bool rememberPassword = m_checkRememberPassword->isChecked();

    ConfigManager::setRememberEmail(rememberEmail);
    ConfigManager::setRememberPassword(rememberPassword);
    ConfigManager::sync();

}

void LoginDialog::onRememberPasswordChanged(int state)
{

    // 如果取消记住密码，清空输入框并删除已保存的密码
    if (state == Qt::Unchecked) {
        m_editPassword->clear();
        // 删除已保存的加密密码，保持数据一致性
        ConfigManager::setEncryptedPassword("");
    }

    // 保存记住选项状态
    bool rememberEmail = m_checkRememberEmail->isChecked();
    bool rememberPassword = m_checkRememberPassword->isChecked();

    ConfigManager::setRememberEmail(rememberEmail);
    ConfigManager::setRememberPassword(rememberPassword);
    ConfigManager::sync();

}

bool LoginDialog::validateInput()
{
    QString email = m_editEmail->text().trimmed();
    QString password = m_editPassword->text();


    if (email.isEmpty()) {
        showStatus(tr("请输入邮箱地址"), "error");
        m_editEmail->setFocus();
        return false;
    }

    if (!email.contains("@") || !email.contains(".")) {
        showStatus(tr("请输入有效的邮箱地址"), "error");
        m_editEmail->setFocus();
        return false;
    }

    if (password.isEmpty()) {
        showStatus(tr("请输入密码"), "error");
        m_editPassword->setFocus();
        return false;
    }

    if (password.length() < 6) {
        showStatus(tr("密码长度不能少于6位"), "error");
        m_editPassword->setFocus();
        return false;
    }

    return true;
}

void LoginDialog::performLogin()
{

    // 安全检查
    if (!ANTI_DEBUG_CHECK()) {
        showStatus(tr("检测到调试环境，登录被拒绝"), "error");
        return;
    }

    if (!INTEGRITY_CHECK()) {
        showStatus(tr("文件完整性验证失败"), "error");
        return;
    }

    if (!validateAuthIntegrity()) {
        showStatus(tr("授权验证失败"), "error");
        return;
    }


    showStatus(tr("正在登录..."), "loading");
    setLoginEnabled(false);
    protectAuthData();

    // 构建URL和请求

    QUrl url(m_apiBase);

    QNetworkRequest req(url);

    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
    req.setRawHeader("Accept", "application/json");
    req.setRawHeader("Accept-Charset", "utf-8");
    req.setRawHeader("User-Agent", generateUserAgent().toUtf8());
    req.setRawHeader("Accept-Encoding", "gzip, deflate");
    req.setRawHeader("Connection", "keep-alive");



    // 构建JSON载荷
    QByteArray jsonData = buildLoginPayload();

    m_reply = m_nam.post(req, jsonData);

    if (m_reply) {
        connect(m_reply, &QNetworkReply::finished, this, &LoginDialog::onRequestFinished);
    } else {
        showStatus(tr("网络请求创建失败"), "error");
        setLoginEnabled(true);
    }
}

QByteArray LoginDialog::buildLoginPayload() const
{

    QString machineCode = Protection::machineIDHashKey();
    QString userAgent = generateUserAgent();
    QString osInfo = getOSInfo();
    QString appVersion = LimeReader::AppVersion::getAppVersion();  // 使用统一版本管理系统
    QString platform = getPlatformString();


    // 构建设备信息对象（符合新规范）
    QJsonObject deviceInfo;
    deviceInfo["name"] = "LimeReader";  // 固定设备名称
    deviceInfo["type"] = "client";      // 固定设备类型
    deviceInfo["userAgent"] = userAgent;
    deviceInfo["os"] = osInfo;
    deviceInfo["appVersion"] = appVersion;


    // 构建登录载荷（遵循新API规范）
    QJsonObject payload;
    payload["email"] = m_editEmail->text().trimmed();
    payload["password"] = m_editPassword->text();
    payload["machineCode"] = machineCode;
    payload["deviceInfo"] = deviceInfo;
    payload["clientName"] = "LimeReader";  // 必填字段：固定值
    payload["currentVersion"] = appVersion; // 必填字段：客户端当前版本号
    payload["platform"] = platform;         // 必填字段：客户端平台


    QJsonDocument doc(payload);
    QByteArray jsonData = doc.toJson(QJsonDocument::Compact);

    // Qt的QJsonDocument::toJson默认输出UTF-8字节序列，直接发送QByteArray即可，无需额外转码

    // 验证UTF-8编码（可选的调试步骤）
    QString verification = QString::fromUtf8(jsonData);
    if (verification.toUtf8() != jsonData) {
    } else {
    }

    return jsonData;
}

void LoginDialog::onRequestFinished()
{

    if (!m_reply) {
        return;
    }

    setLoginEnabled(true);

    // 检查网络错误
    QNetworkReply::NetworkError error = m_reply->error();
    int httpStatus = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QString httpStatusText = m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();


    // 读取响应数据 - 无论是否有网络错误都需要读取
    QByteArray responseData = m_reply->readAll();

    // 如果有网络错误，先尝试解析JSON获取具体错误信息
    if (error != QNetworkReply::NoError) {
        QString errorString = m_reply->errorString();

        // 尝试解析JSON响应获取具体错误信息
        if (!responseData.isEmpty() && (httpStatus == 400 || httpStatus == 403 || httpStatus == 429)) {
            QString responseText = QString::fromUtf8(responseData);

            QJsonParseError parseError;
            QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);

            if (parseError.error == QJsonParseError::NoError) {
                QJsonObject response = doc.object();
                QString serverError = response.value("error").toString();
                QString serverMessage = response.value("message").toString();


                // 显示服务器返回的具体错误信息
                if (serverError == "DEVICE_LIMIT_EXCEEDED") {
                    showStatus(tr("设备数量超出限制，请登录网站管理设备"), "error");
                } else if (serverError == "INVALID_CREDENTIALS") {
                    showStatus(tr("邮箱或密码错误"), "error");
                } else if (!serverMessage.isEmpty()) {
                    showStatus(serverMessage, "error");
                } else {
                    showStatus(tr("请求失败: HTTP %1 - %2").arg(httpStatus).arg(httpStatusText), "error");
                }
            } else {
                showStatus(tr("网络连接失败: %1").arg(errorString), "error");
            }
        } else {
            showStatus(tr("网络连接失败: %1").arg(errorString), "error");
        }

        m_reply->deleteLater();
        m_reply = nullptr;
        return;
    }


    m_reply->deleteLater();
    m_reply = nullptr;

    // 直接解析JSON响应
    QString responseText = QString::fromUtf8(responseData);

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        showStatus(tr("服务器响应格式错误: %1").arg(parseError.errorString()), "error");
        return;
    } else {
    }

    QJsonObject response = doc.object();
    bool success = response.value("success").toBool();

    if (success) {

        // 登录成功 - 获取新的authToken
        QString authToken = response.value("token").toString();
        m_email = m_editEmail->text().trimmed();
        m_deviceName = m_editDeviceName->text();
        m_apiBase = m_editApiBase->text();

        // 注意：登录对话框使用完整的登录URL，不要修正
        // 只有ApiManager需要修正为基础API路径


        // 设置m_token变量（保持向后兼容）
        m_token = authToken;

        // 使用新的API管理系统保存token
        m_apiManager->setAuthToken(authToken);

        ConfigManager::setAuthToken(authToken);

        // 检查用户类型
        QJsonObject user = response.value("user").toObject();

        // 详细打印用户信息中的每个字段
        for (auto it = user.begin(); it != user.end(); ++it) {
            QString key = it.key();
            QJsonValue value = it.value();
            if (value.isObject()) {
                QJsonObject obj = value.toObject();
            } else if (value.isArray()) {
                QJsonArray arr = value.toArray();
            } else {
            }
        }

        QString utype = user.value("type").toString();

        if (utype.isEmpty()) {
            if (user.contains("subscription") && user.value("subscription").isObject()) {
                QJsonObject subscription = user.value("subscription").toObject();

                // 详细打印订阅信息中的每个字段
                for (auto it = subscription.begin(); it != subscription.end(); ++it) {
                    QString key = it.key();
                    QJsonValue value = it.value();
                    if (value.isObject()) {
                        QJsonObject obj = value.toObject();
                    } else if (value.isArray()) {
                        QJsonArray arr = value.toArray();
                    } else {
                    }
                }

                utype = subscription.value("type").toString();

                // 特别检查到期时间相关字段
                if (subscription.contains("expiresAt")) {
                    QString expiresAt = subscription.value("expiresAt").toString();
                }
                if (subscription.contains("endDate")) {
                    QString endDate = subscription.value("endDate").toString();
                }
                if (subscription.contains("expiry")) {
                    QString expiry = subscription.value("expiry").toString();
                }

                // 保存订阅信息到本地
                ConfigManager::setSubscriptionInfo(subscription);
            } else {
                // 即使没有订阅信息也要保存空对象，确保本地存在记录
                ConfigManager::setSubscriptionInfo(QJsonObject());
            }
        } else {
        }

        QString freeStr = OBFUSCATE_STR("free");
        s_isTrialUser = (utype.compare(freeStr, Qt::CaseInsensitive) == 0);

        // 检查登录响应中的版本更新信息
        if (response.contains("updateInfo") && response["updateInfo"].isObject()) {
            QJsonObject updateInfo = response["updateInfo"].toObject();
            bool hasUpdate = updateInfo.value("hasUpdate").toBool();

            if (hasUpdate) {
                QString latestVersion = updateInfo.value("latestVersion").toString();
                QString updateUrl = updateInfo.value("updateUrl").toString();
                QString updateLog = updateInfo.value("updateLog").toString();
                QString checksumMD5 = updateInfo.value("checksumMD5").toString();


                if (!latestVersion.isEmpty() && !updateUrl.isEmpty()) {
                    // 通过ApiManager发射版本信息信号
                    m_apiManager->notifyVersionInfo(latestVersion, updateUrl, updateLog, checksumMD5);
                }
            } else {
            }
        } else {
        }

        // 直接通知订阅信息给UserInfoDialog
        if (user.contains("subscription") && user.value("subscription").isObject()) {
            QJsonObject subscription = user.value("subscription").toObject();
            m_apiManager->notifySubscriptionInfo(subscription);
        }

        // 启动心跳保活
        if (m_apiManager->hasValidToken()) {
            m_apiManager->startHeartbeat();
        }

        showStatus(tr("登录成功"), "success");
        saveToIni();

        // 延迟关闭对话框
        QTimer::singleShot(1000, this, &QDialog::accept);
    } else {

        // 登录失败
        QString error = response.value("error").toString();
        QString message = response.value("message").toString();


        if (error == "DEVICE_LIMIT_EXCEEDED") {
            showStatus(tr("设备数量超出限制，请登录网站管理设备"), "error");
        } else if (error == "INVALID_CREDENTIALS") {
            showStatus(tr("邮箱或密码错误"), "error");
        } else if (!message.isEmpty()) {
            showStatus(message, "error");
        } else {
            showStatus(tr("登录失败，请重试"), "error");
        }
    }
}

bool LoginDialog::validateAuthIntegrity()
{
    // 这里可以添加更多的授权验证逻辑
    return true;
}

void LoginDialog::protectAuthData()
{
    // 保护认证数据，这里可以添加更多保护措施
    OBFUSCATE_FLOW(true, {}, {});
}

void LoginDialog::showStatus(const QString& message, const QString& type)
{
    if (message.isEmpty()) {
        m_labelStatus->setVisible(false);
        return;
    }

    m_labelStatus->setText(message);
    m_labelStatus->setProperty("type", type);
    m_labelStatus->style()->polish(m_labelStatus);
    m_labelStatus->setVisible(true);

    // 5秒后自动隐藏成功消息
    if (type == "success") {
        QTimer::singleShot(5000, this, [this]() {
            m_labelStatus->setVisible(false);
        });
    }
}

void LoginDialog::setLoginEnabled(bool enabled)
{
    m_btnLogin->setEnabled(enabled);
    m_editEmail->setEnabled(enabled);
    m_editPassword->setEnabled(enabled);
}

QString LoginDialog::generateDeviceName() const
{
    QString machineHash = Protection::machineIDHashKey();
    return QString("Device_%1").arg(machineHash.left(8));
}

QString LoginDialog::generateUserAgent() const
{
    QString appName = QCoreApplication::applicationName();
    if (appName.isEmpty()) {
        appName = "LongImageReader";
    }

    // 使用统一的版本管理系统
    QString version = LimeReader::AppVersion::getAppVersion();

    QString os = getOSInfo();

    // 确保只包含ASCII字符，避免编码问题
    QString userAgent = QString("%1/%2 (%3)").arg(appName, version, os);

    // 验证User-Agent是否只包含ASCII字符
    for (int i = 0; i < userAgent.length(); ++i) {
        if (userAgent[i].unicode() > 127) {
            userAgent[i] = '_';
        }
    }

    return userAgent;
}

QString LoginDialog::getOSInfo() const
{
#ifdef Q_OS_WIN
    return "Windows";
#elif defined(Q_OS_MAC)
    return "macOS";
#elif defined(Q_OS_LINUX)
    return "Linux";
#else
    return "Unknown";
#endif
}

QString LoginDialog::getPlatformString() const
{
    // 根据新API规范返回平台标识
#ifdef Q_OS_WIN
    return "windows";
#elif defined(Q_OS_MAC)
    return "macos";
#elif defined(Q_OS_LINUX)
    return "linux";
#else
    return "unknown";
#endif
}